//
//  MeViewController.swift
//  AntProj
//
//  Created by 陈宇 on 2017/5/2.
//  Copyright © 2017年 🐜. All rights reserved.
//

import UIKit
import Haneke
import RxSwift

class MeViewController: UITableViewController {
    
    lazy var disposeBag = DisposeBag()
    
    @IBOutlet weak var avatarView: UIImageView!
    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var emailLabel: UILabel!
    @IBOutlet weak var mobileLabel: UILabel!
    @IBOutlet weak var btn_logout: UIButton!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        title = "Me"
        addLeftBarButtonWithImage(#imageLiteral(resourceName: "menu"))
        btn_logout.setBackgroundImage(UIImage.image(with: APP.APP_PRIMARY_COLOR, size: CGSize(width: 1, height: 1)), for: .normal)
        
        configureEvents()
        
        self.refreshInfo()
        Observable<Int>.interval(30, scheduler: MainScheduler.instance).subscribe(onNext: { (_) in
            self.refreshInfo()
        }).addDisposableTo(disposeBag)
        
    }
    
    func refreshInfo() {
        api.request(.Info).unWrapper().mapObject(type: Member.self).subscribe(onNext: { (member) in
            guard let member = member else { return }
            
            self.avatarView.hnk_setImageFromURL(member.avatar)
            self.nameLabel.text = member.name
            self.emailLabel.text = member.email
            self.mobileLabel.text = member.phone
        }).addDisposableTo(disposeBag)
    }
    
    func configureEvents() {
        btn_logout.rx.tap.bind {
            UIApplication.token = nil
            self.toMain()
        }.addDisposableTo(disposeBag)
    }
    
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 15
    }
    
    override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)

        if indexPath.row == 0 {
            showUpdateAvatar()
        } else if indexPath.row == 1 {
            showUpdate(nameLabel, title: "更新姓名".localized())
        } else if indexPath.row == 3 {
            showUpdate(mobileLabel, title: "更新手机".localized(), keyboardType: .numberPad)
        }
    }
}

extension MeViewController {
    func showUpdateAvatar() {
        let actionSheet = UIAlertController(title: "", message: "修改头像".localized(), preferredStyle: .actionSheet)
        if (UIImagePickerController.isSourceTypeAvailable(.camera)) {
            actionSheet.addAction(UIAlertAction(title: "拍照".localized(), style: .default, handler: { (action) in
                showImagePicker(.camera)
            }))
        }
        actionSheet.addAction(UIAlertAction(title: "从手机相册选择".localized(), style: .default, handler: { (action) in
            showImagePicker(.photoLibrary)
        }))
        actionSheet.addAction(UIAlertAction(title: "取消".localized(), style: .cancel, handler: nil))
        present(actionSheet, animated: true, completion: nil)
        
        func showImagePicker(_ sourceType: UIImagePickerControllerSourceType) {
            UIImagePickerController.rx.createWithParent(self, configureImagePicker: { (picker) in
                picker.sourceType = sourceType
                picker.allowsEditing = false
            }).flatMap({ $0.rx.didFinishPickingMediaWithInfo }).take(1).map({ $0[UIImagePickerControllerOriginalImage] as? UIImage }).asDriver(onErrorJustReturn: UIImage(named: "")).drive(self.avatarView.rx.image).addDisposableTo(self.disposeBag)
        }
    }
    
    func showUpdate(_ label: UILabel, title: String, keyboardType: UIKeyboardType = .default) {
        let alert = UIAlertController(title: title, message: "".localized(), preferredStyle: .alert)
        
        alert.addTextField { (textField) in
            textField.text = label.text
            textField.keyboardType = keyboardType
        }
        alert.addAction(UIAlertAction(title: "确定".localized(), style: .default, handler: {(action) in
            guard let text = alert.textFields?.first?.text else {
                return
            }
            if text.isEmpty {
                UIApplication.whisper(title: "不能为空")
                return
            }
            
            label.text = text
        }))
        alert.addAction(UIAlertAction(title: "取消".localized(), style: .cancel, handler: nil))
        present(alert, animated: true, completion: nil)
    }
}
